package com.haha.keymap.v4;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.haha.keymap.v1.CustomPoint;
import com.haha.keymap.v1.SkillConfigData;
import com.haha.keymap.v1.SkillInfo;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import org.jnativehook.GlobalScreen;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

import java.awt.*;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shenlinnan
 * @date 2025/7/20 20:02
 */
public class ConfigController implements NativeKeyListener {

    private MainApp mainApp;
    private MainController mainController;

    @FXML
    private Label coord1Label;
    @FXML
    private Label step2Label;
    @FXML
    private Label step3Label;
    @FXML
    private Label coord2Label;
    @FXML
    private Label coord3Label;
    @FXML
    private Label coord4Label;

    /**
     * 存储第一步坐标
     */
    private Point point1;

    /**
     * 存储第二步坐标
     */
    private Point point2;

    /**
     * 存储第三步坐标
     */
    private Point point3;

    /**
     * 存储第四步坐标
     */
    private Point point4;

    private int step = 1;

    public void setMainApp(MainApp mainApp) {
        this.mainApp = mainApp;
    }

    @FXML
    private void handleSaveConfigButtonAction() {
        // 保存配置逻辑...
        saveConfigToFile();
        saveAoeConfigToFile();

        //mainController.setSkillConfigData(CommonUtil.getConfigInfo());

        // 关闭配置窗口
        if (mainApp != null) {
            mainApp.hideConfigDialog();
        }
    }

    @Override
    public void nativeKeyTyped(NativeKeyEvent nativeKeyEvent) {

    }

    @Override
    public void nativeKeyPressed(NativeKeyEvent nativeKeyEvent) {
        if (nativeKeyEvent.getKeyCode() == NativeKeyEvent.VC_F11) {
            System.out.println("按了F11...");
            if (step == 1) {
                java.awt.Point mousePos = java.awt.MouseInfo.getPointerInfo().getLocation();

                // 在JavaFX线程中更新UI
                javafx.application.Platform.runLater(() -> {
                    coord1Label.setText(String.format("坐标: (X:%d, Y:%d)", mousePos.x, mousePos.y));
                    step2Label.setVisible(true);
                    coord2Label.setVisible(true);
                });
                // 保存第一步坐标
                point1 = mousePos;
                step = 2;
            } else if (step == 2) {
                java.awt.Point mousePos = java.awt.MouseInfo.getPointerInfo().getLocation();
                // 保存第二步坐标
                point2 = mousePos;

                // 在JavaFX线程中更新UI
                javafx.application.Platform.runLater(() -> {
                    coord2Label.setText(String.format("坐标: (X:%d, Y:%d)", mousePos.x, mousePos.y));
                    step3Label.setVisible(true);
                    coord3Label.setVisible(true);
                });
                step = 3;
            } else if (step == 3) {
                java.awt.Point mousePos = java.awt.MouseInfo.getPointerInfo().getLocation();
                // 保存第二步坐标
                point3 = mousePos;

                // 在JavaFX线程中更新UI
                javafx.application.Platform.runLater(() -> {
                    coord3Label.setText(String.format("坐标: (X:%d, Y:%d)", mousePos.x, mousePos.y));
                });
                step = 4;
            } else if (step == 4) {
                java.awt.Point mousePos = java.awt.MouseInfo.getPointerInfo().getLocation();
                // 保存第二步坐标
                point4 = mousePos;

                // 在JavaFX线程中更新UI
                javafx.application.Platform.runLater(() -> {
                    coord4Label.setText(String.format("坐标: (X:%d, Y:%d)", mousePos.x, mousePos.y));
                });
            }
        }
    }

    @Override
    public void nativeKeyReleased(NativeKeyEvent nativeKeyEvent) {

    }

    /**
     * 注册键盘监听器
     */
    public void registerKeyListener() {
        try {
            GlobalScreen.addNativeKeyListener(this);
            System.out.println("配置键盘监听器已注册");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 注销键盘监听器
     */
    public void unregisterKeyListener() {
        GlobalScreen.removeNativeKeyListener(this);
        System.out.println("配置键盘监听器已注销");
    }

    /**
     * 重置配置窗口状态
     */
    public void reset() {
        // 重置步骤
        step = 1;

        // 重置UI状态
        javafx.application.Platform.runLater(() -> {
            // 重置坐标标签
            coord1Label.setText("坐标：尚未记录");
            coord2Label.setText("坐标：尚未记录");

            // 隐藏第二步组件
            step2Label.setVisible(false);
            coord2Label.setVisible(false);
        });
    }

    private void saveConfigToFile() {
        // 检查是否完成所有配置步骤
        if (point1 == null || point2 == null) {
            System.out.println("请先完成所有配置步骤！");
            return;
        }

        // 创建配置对象
        SkillConfigData config = new SkillConfigData();

        // 添加坐标点
        List<CustomPoint> points = new ArrayList<>();
        points.add(new CustomPoint(point1.x, point1.y));
        points.add(new CustomPoint(point2.x, point2.y));
        config.setPoint(points);

        // 添加技能配置（示例数据）
        List<SkillInfo> skills = new ArrayList<>();
        // ... 添加技能配置 ...
        config.setSkills(skills);

        // 保存到文件
        String currentDir = System.getProperty("user.dir");
        String selectedTalentLabelText = mainController.getSelectedTalentLabelText();
        String filePath = Paths.get(currentDir, selectedTalentLabelText + "-config.json").toString();

        // 使用Gson保存JSON
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        try (FileWriter writer = new FileWriter(filePath)) {
            gson.toJson(config, writer);
            System.out.println("配置已保存到: " + filePath);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void saveAoeConfigToFile() {
        // 检查是否完成所有配置步骤
        if (point3 == null || point4 == null) {
            System.out.println("请先完成所有配置步骤！");
            return;
        }

        // 创建配置对象
        SkillConfigData config = new SkillConfigData();

        // 添加坐标点
        List<CustomPoint> points = new ArrayList<>();
        points.add(new CustomPoint(point3.x, point3.y));
        points.add(new CustomPoint(point4.x, point4.y));
        config.setPoint(points);

        // 添加技能配置（示例数据）
        List<SkillInfo> skills = new ArrayList<>();
        // ... 添加技能配置 ...
        config.setSkills(skills);

        // 保存到文件
        String currentDir = System.getProperty("user.dir");
        String selectedTalentLabelText = mainController.getSelectedTalentLabelText();
        String filePath = Paths.get(currentDir, selectedTalentLabelText + "-aoe-config.json").toString();

        // 使用Gson保存JSON
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        try (FileWriter writer = new FileWriter(filePath)) {
            gson.toJson(config, writer);
            System.out.println("配置已保存到: " + filePath);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void setMainController(MainController mainController) {
        this.mainController = mainController;
    }
}
